export default class DownTime {
    private downTask: any = new Set();
    constructor() { }

    public getTask() {
        return this.downTask;
    }

    /**
     * 结束任务
     * @param proxy 代理地址
     * @returns 
     */
    public taskEnd(proxy: any) {
        if (!this.downTask.has(proxy.key)) return;
        proxy.countTime = 0;
        this.downTask.delete(proxy.key)
        if (proxy.timerID) {
            console.log('proxy', proxy)
            // 清除定时器
            clearInterval(proxy.timerID);
            proxy.timerID = null;
        }
    }

    /**
     * 开始任务
     * @param proxy 代理地址
     * @param timestamp 时间戳 
     * @param spar 分隔符
     * @returns 
     */
    public startTask(proxy: any, timestamp = 0, spar = '：') {
        if (this.downTask.has(proxy.key)) return;
        this.downTask.add(proxy.key)
        if (timestamp.toString().length == 13) timestamp = Math.round(timestamp / 1000);
        if (timestamp <= 0) this.taskEnd(proxy);
        this.formantTime(proxy,timestamp, spar);
        proxy.timerID = setInterval(() => {
            timestamp--;
            proxy.countTime = timestamp
            if (timestamp <= 0) {
                this.taskEnd(proxy)
                return;
            }
            this.formantTime(proxy,timestamp, spar);
        }, 1000);
        return proxy;
    }

    /**
     * 格式化时间
     * @param proxy 引用地址
     * @param timestamp 引用时间戳 / 秒
     * @param spar 时间分隔符
     */
    private formantTime(proxy: any, timestamp: number, spar: string = '：') {
        let day: number | string = 0;
        let hour: number | string = 0;
        let min: number | string = 0;
        let second: number | string = 0;
        const d = Math.floor(timestamp / 60 / 60 / 24);
        const h = Math.floor((timestamp / 60 / 60) % 24);
        const m = Math.floor((timestamp / 60) % 60);
        const s = Math.floor(timestamp % 60);
        day = d < 10 ? '0' + d : d;
        hour = h < 10 ? '0' + h : h;
        min = m < 10 ? '0' + m : m;
        second = s < 10 ? '0' + s : s;
        if (day != '00' || Number(day) != 0) {
            proxy.downTime = day + spar + hour + spar + min + spar + second;
        } else if (hour != '00' || Number(hour) != 0) {
            proxy.downTime = hour + spar + min + spar + second;
        } else {
            proxy.downTime = min + spar + second;
        }
    }

}